<template>
  <div class="bookset-manager">
    <!-- 步骤导航 -->
    <div class="step-navigation">
      <el-steps :active="currentStep" align-center>
        <el-step title="基本信息" description="绘本集基础设置" />
        <el-step title="绘本管理" description="添加和管理绘本" />
        <el-step title="页面管理" description="编辑绘本页面" />
        <el-step title="预览提交" description="预览和保存" />
      </el-steps>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 左侧编辑区域 -->
        <el-col :span="16">
          <div class="edit-area">
            <!-- 步骤1：基本信息 -->
            <div v-show="currentStep === 0" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>📖 绘本集基本信息</span>
                  </div>
                </template>

                <el-form ref="basicFormRef" :model="bookSetData.basic" :rules="basicFormRules" label-width="120px">
                  <el-form-item label="绘本集标题" prop="title">
                    <el-input
                      v-model="bookSetData.basic.title"
                      placeholder="请输入绘本集标题"
                      maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item label="语言类型" prop="language">
                    <el-select v-model="bookSetData.basic.language" placeholder="请选择语言类型" style="width: 100%">
                      <el-option label="英文" value="en" />
                      <el-option label="中文" value="zh" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="分类" prop="categoryId">
                    <el-select v-model="bookSetData.basic.categoryId" placeholder="请选择分类" style="width: 100%">
                      <el-option
                        v-for="category in filteredCategories"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                      />
                    </el-select>
                    <div class="category-tips">
                      <el-text size="small" type="info">
                        💡 分类会根据选择的语言类型自动筛选
                      </el-text>
                    </div>
                  </el-form-item>

                  <el-form-item label="适龄范围" prop="ageRange">
                    <div class="age-range-container">
                      <el-select
                        v-model="bookSetData.basic.ageRange"
                        placeholder="请选择适龄范围"
                        style="width: 100%"
                        filterable
                        allow-create
                        @change="handleAgeRangeChange"
                        @blur="handleAgeRangeBlur"
                      >
                        <el-option label="0-2岁 (婴幼儿)" value="0-2岁" />
                        <el-option label="2-3岁 (学步期)" value="2-3岁" />
                        <el-option label="3-4岁 (幼儿园小班)" value="3-4岁" />
                        <el-option label="4-5岁 (幼儿园中班)" value="4-5岁" />
                        <el-option label="5-6岁 (幼儿园大班)" value="5-6岁" />
                        <el-option label="6-7岁 (学前班)" value="6-7岁" />
                        <el-option label="7-8岁 (小学一年级)" value="7-8岁" />
                        <el-option label="8-9岁 (小学二年级)" value="8-9岁" />
                        <el-option label="9-10岁 (小学三年级)" value="9-10岁" />
                        <el-option label="10-12岁 (小学高年级)" value="10-12岁" />
                        <el-option label="3-6岁 (学龄前)" value="3-6岁" />
                        <el-option label="6-12岁 (小学阶段)" value="6-12岁" />
                        <el-option label="0-12岁 (全年龄段)" value="0-12岁" />
                      </el-select>
                      <div class="age-range-tips">
                        <el-text size="small" type="info">
                          💡 可选择预设范围或输入自定义范围（如：4-7岁）
                        </el-text>
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item label="难度等级" prop="difficulty">
                    <el-select v-model="bookSetData.basic.difficulty" placeholder="请选择难度等级" style="width: 100%">
                      <el-option label="入门" value="beginner" />
                      <el-option label="初级" value="elementary" />
                      <el-option label="中级" value="intermediate" />
                      <el-option label="高级" value="advanced" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="绘本集描述" prop="description">
                    <el-input
                      v-model="bookSetData.basic.description"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入绘本集描述"
                      maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>

                  <el-form-item label="来源" prop="source">
                    <el-input
                      v-model="bookSetData.basic.source"
                      placeholder="请输入绘本集来源（如：牛津大学出版社）"
                      maxlength="100"
                      show-word-limit
                    />
                    <div class="source-tips">
                      <el-text size="small" type="info">
                        💡 标识绘本集的来源或出版社，便于分类管理
                      </el-text>
                    </div>
                  </el-form-item>

                  <el-form-item label="是否推荐" prop="isRecommended">
                    <el-switch
                      v-model="bookSetData.basic.isRecommended"
                      active-text="推荐"
                      inactive-text="不推荐"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                    />
                    <div class="recommend-tips">
                      <el-text size="small" type="info">
                        💡 推荐的绘本集将在首页和推荐列表中优先展示
                      </el-text>
                    </div>
                  </el-form-item>

                  <el-form-item label="绘本集封面" prop="coverUrl">
                    <el-upload
                      class="cover-uploader"
                      :action="getBusinessUploadUrl('bookset-cover', bookSetId || 0)"
                      :headers="getBusinessUploadHeaders()"
                      :show-file-list="false"
                      :on-success="handleCoverSuccess"
                      :before-upload="beforeCoverUpload"
                      accept="image/*"
                      name="cover"
                    >
                      <img v-if="bookSetData.basic.coverUrl" :src="bookSetData.basic.coverUrl" class="cover-image" />
                      <div v-else class="cover-placeholder">
                        <el-icon class="cover-icon"><Plus /></el-icon>
                        <div class="cover-text">点击上传封面</div>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>

            <!-- 步骤2：绘本管理 -->
            <div v-show="currentStep === 1" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>📚 绘本管理</span>
                    <el-button type="primary" @click="addBook">添加绘本</el-button>
                  </div>
                </template>

                <div v-if="bookSetData.books.length === 0" class="empty-state">
                  <el-empty description="还没有添加绘本">
                    <el-button type="primary" @click="addBook">添加第一个绘本</el-button>
                  </el-empty>
                </div>

                <div v-else class="books-list">
                  <el-row :gutter="20">
                    <el-col
                      v-for="(book, index) in bookSetData.books"
                      :key="book.id || index"
                      :span="8"
                      style="margin-bottom: 20px;"
                    >
                      <el-card class="book-card">
                        <template #header>
                          <div class="book-header">
                            <span>绘本 {{ index + 1 }}</span>
                            <div class="book-actions">
                              <el-button size="small" type="primary" @click="editBook(index)">编辑</el-button>
                              <el-button size="small" type="danger" @click="removeBook(index)">删除</el-button>
                            </div>
                          </div>
                        </template>

                        <div class="book-display">
                          <div class="book-cover-container">
                            <img v-if="book.coverUrl" :src="book.coverUrl" class="book-cover" />
                            <div v-else class="cover-placeholder">
                              <el-icon><Picture /></el-icon>
                              <div>暂无封面</div>
                            </div>
                          </div>

                          <div class="book-info">
                            <h4>{{ book.title || '未命名绘本' }}</h4>
                            <p class="book-description">{{ book.description || '暂无描述' }}</p>
                            <div class="book-stats">
                              <el-tag size="small" type="info">{{ book.pages?.length || 0 }} 页</el-tag>
                              <el-tag size="small" type="success">排序: {{ book.sort || index + 1 }}</el-tag>
                            </div>
                          </div>
                        </div>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
              </el-card>
            </div>

            <!-- 步骤3：页面管理 -->
            <div v-show="currentStep === 2" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>📄 页面管理</span>
                    <div class="header-actions">
                      <el-select v-model="selectedBookIndex" placeholder="选择绘本" clearable style="width: 200px; margin-right: 10px;">
                        <el-option
                          v-for="(book, index) in bookSetData.books"
                          :key="index"
                          :label="`${book.title || '未命名绘本'} (${book.pages?.length || 0}页)`"
                          :value="index"
                        />
                      </el-select>
                      <el-button type="primary" @click="addPage" :disabled="selectedBookIndex === null">
                        添加页面
                      </el-button>
                    </div>
                  </div>
                </template>

                <div v-if="selectedBookIndex === null" class="empty-state">
                  <el-empty description="请先选择一个绘本来管理页面" />
                </div>

                <div v-else-if="currentBook.pages.length === 0" class="empty-state">
                  <el-empty description="该绘本还没有页面">
                    <el-button type="primary" @click="addPage">添加第一页</el-button>
                  </el-empty>
                </div>

                <div v-else class="pages-container">
                  <div class="pages-grid">
                    <div
                      v-for="(page, pageIndex) in currentBook.pages"
                      :key="page.id || pageIndex"
                      class="page-item"
                    >
                      <el-card class="page-card">
                        <template #header>
                          <div class="page-header">
                            <span>第 {{ page.pageNumber || pageIndex + 1 }} 页</span>
                            <div class="page-actions">
                              <el-button size="small" type="primary" @click="editPage(pageIndex)">编辑</el-button>
                              <el-button size="small" type="danger" @click="removePage(pageIndex)">删除</el-button>
                            </div>
                          </div>
                        </template>

                        <div class="page-display">
                          <div class="page-image-container">
                            <img v-if="page.imageUrl" :src="page.imageUrl" class="page-image" />
                            <div v-else class="image-placeholder">
                              <el-icon><Picture /></el-icon>
                              <div>暂无图片</div>
                            </div>
                          </div>

                          <div class="page-content">
                            <div class="text-content">
                              <p>{{ page.textContent || '暂无文本内容' }}</p>
                            </div>

                            <div v-if="page.officialAudioUrl" class="audio-info">
                              <span class="label">音频：</span>
                              <el-tag type="success" size="small">已上传</el-tag>
                            </div>
                          </div>
                        </div>
                      </el-card>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>

            <!-- 步骤4：预览提交 -->
            <div v-show="currentStep === 3" class="step-content">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>🔍 最终预览</span>
                  </div>
                </template>

                <div class="final-preview">
                  <el-alert
                    :title="validationResult.title"
                    :type="validationResult.type"
                    :description="validationResult.description"
                    show-icon
                    :closable="false"
                    style="margin-bottom: 20px"
                  />

                  <div class="bookset-overview">
                    <h3>绘本集信息</h3>
                    <div class="info-grid">
                      <div class="info-item">
                        <span class="label">标题：</span>
                        <span>{{ bookSetData.basic.title || '未设置' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">语言：</span>
                        <span>{{ getLanguageText(bookSetData.basic.language) }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">来源：</span>
                        <span>{{ bookSetData.basic.source || '未设置' }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">推荐状态：</span>
                        <el-tag :type="bookSetData.basic.isRecommended ? 'success' : 'info'" size="small">
                          {{ bookSetData.basic.isRecommended ? '推荐' : '普通' }}
                        </el-tag>
                      </div>
                      <div class="info-item">
                        <span class="label">绘本数量：</span>
                        <span>{{ bookSetData.books.length }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">总页数：</span>
                        <span>{{ totalPages }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </el-col>

        <!-- 右侧预览区域 -->
        <el-col :span="8">
          <div class="preview-area">
            <el-card class="preview-card">
              <template #header>
                <div class="preview-header">
                  <span>实时预览</span>
                  <el-tag :type="getValidationTagType()">{{ getValidationText() }}</el-tag>
                </div>
              </template>

              <div class="preview-content">
                <div v-if="currentStep === 0" class="step-preview">
                  <h4>绘本集基本信息</h4>
                  <div v-if="bookSetData.basic.coverUrl" class="cover-section">
                    <img :src="bookSetData.basic.coverUrl" class="preview-cover" />
                  </div>
                  <div class="info-section">
                    <div class="info-item">
                      <span class="label">标题：</span>
                      <span>{{ bookSetData.basic.title || '未设置' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">语言：</span>
                      <span>{{ getLanguageText(bookSetData.basic.language) }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">来源：</span>
                      <span>{{ bookSetData.basic.source || '未设置' }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">推荐状态：</span>
                      <el-tag :type="bookSetData.basic.isRecommended ? 'success' : 'info'" size="small">
                        {{ bookSetData.basic.isRecommended ? '推荐' : '普通' }}
                      </el-tag>
                    </div>
                  </div>
                </div>

                <div v-else-if="currentStep === 1" class="step-preview">
                  <h4>绘本列表 ({{ bookSetData.books.length }}个)</h4>
                  <div v-if="bookSetData.books.length === 0" class="empty-preview">
                    <el-empty description="还没有添加绘本" :image-size="80" />
                  </div>
                  <div v-else class="books-preview">
                    <div
                      v-for="(book, index) in bookSetData.books"
                      :key="index"
                      class="book-preview-item"
                    >
                      <div class="book-cover">
                        <img v-if="book.coverUrl" :src="book.coverUrl" class="book-cover-img" />
                        <div v-else class="no-cover">无封面</div>
                      </div>
                      <div class="book-info">
                        <div class="book-title">{{ book.title || '未命名绘本' }}</div>
                        <div class="book-stats">
                          <el-tag size="small">{{ book.pages?.length || 0 }} 页</el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div v-else-if="currentStep === 2" class="step-preview">
                  <h4>页面总览</h4>
                  <div class="pages-stats">
                    <div class="stat-item">
                      <div class="stat-number">{{ totalPages }}</div>
                      <div class="stat-label">总页数</div>
                    </div>
                  </div>
                </div>

                <div v-else-if="currentStep === 3" class="step-preview">
                  <h4>完整预览</h4>
                  <div class="final-stats">
                    <div class="stats-grid">
                      <div class="stat-card">
                        <div class="stat-number">{{ bookSetData.books.length }}</div>
                        <div class="stat-label">绘本</div>
                      </div>
                      <div class="stat-card">
                        <div class="stat-number">{{ totalPages }}</div>
                        <div class="stat-label">页面</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 底部操作栏 -->
    <div class="footer-actions">
      <el-button @click="handleClose">取消</el-button>
      <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
      <el-button v-if="currentStep < 3" type="primary" @click="nextStep" :disabled="!canProceed">
        下一步
      </el-button>
      <el-button v-if="currentStep === 3" type="success" @click="handleSubmit" :loading="submitting">
        创建绘本集
      </el-button>
    </div>

    <!-- 绘本编辑弹窗 -->
    <el-dialog
      v-model="bookEditVisible"
      title="编辑绘本"
      width="800px"
      :close-on-click-modal="false"
      class="book-edit-dialog"
    >
      <el-form ref="bookFormRef" :model="editingBook" :rules="bookFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="绘本标题" prop="title">
              <el-input
                v-model="editingBook.title"
                placeholder="请输入绘本标题"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="editingBook.sort"
                :min="1"
                :max="100"
                placeholder="排序"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="绘本描述" prop="description">
          <el-input
            v-model="editingBook.description"
            type="textarea"
            :rows="3"
            placeholder="请输入绘本描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="绘本封面" prop="coverUrl">
          <el-upload
            class="book-cover-uploader"
            :action="bookCoverUploadUrl"
            :headers="getBusinessUploadHeaders()"
            :show-file-list="false"
            :on-success="handleBookCoverSuccess"
            :before-upload="beforeBookCoverUpload"
            accept="image/*"
            name="cover"
          >
            <img v-if="editingBook.coverUrl" :src="editingBook.coverUrl" class="book-cover-image" />
            <div v-else class="book-cover-placeholder">
              <el-icon class="cover-icon"><Plus /></el-icon>
              <div class="cover-text">点击上传封面</div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelBookEdit">取消</el-button>
          <el-button type="primary" @click="saveBookEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 页面编辑弹窗 -->
    <el-dialog
      v-model="pageEditVisible"
      title="编辑页面"
      width="900px"
      :close-on-click-modal="false"
      class="page-edit-dialog"
    >
      <el-form ref="pageFormRef" :model="editingPage" :rules="pageFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="页面编号" prop="pageNumber">
              <el-input-number
                v-model="editingPage.pageNumber"
                :min="1"
                :max="100"
                placeholder="页面编号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关键词">
              <el-input
                v-model="keyWordsInput"
                placeholder="请输入关键词，用逗号分隔"
                @blur="updateKeyWords"
              />
              <div class="keywords-display" v-if="editingPage.keyWords.length > 0">
                <el-tag
                  v-for="(keyword, index) in editingPage.keyWords"
                  :key="index"
                  closable
                  @close="removeKeyword(index)"
                  style="margin: 2px;"
                >
                  {{ keyword }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="页面图片" prop="imageUrl">
          <el-upload
            class="page-image-uploader"
            :action="pageImageUploadUrl"
            :headers="getBusinessUploadHeaders()"
            :show-file-list="false"
            :on-success="handlePageImageSuccess"
            :before-upload="beforePageImageUpload"
            accept="image/*"
            name="page"
          >
            <img v-if="editingPage.imageUrl" :src="editingPage.imageUrl" class="page-image-preview" />
            <div v-else class="page-image-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">点击上传页面图片</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="页面文本" prop="textContent">
          <el-input
            v-model="editingPage.textContent"
            type="textarea"
            :rows="4"
            placeholder="请输入页面文本内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文本语言" prop="textLanguage">
              <el-select v-model="editingPage.textLanguage" placeholder="请选择文本语言" style="width: 100%">
                <el-option label="英文" value="english" />
                <el-option label="中文" value="chinese" />
                <el-option label="双语" value="bilingual" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阅读难度" prop="readingDifficulty">
              <el-select v-model="editingPage.readingDifficulty" placeholder="请选择阅读难度" style="width: 100%">
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="官方音频" prop="officialAudioUrl">
          <div class="audio-upload-container">
            <el-upload
              class="audio-uploader"
              :action="pageAudioUploadUrl"
              :headers="getBusinessUploadHeaders()"
              :show-file-list="false"
              :on-success="handleAudioSuccess"
              :before-upload="beforePageAudioUpload"
              accept="audio/*"
              name="audio"
            >
              <el-button type="primary" :icon="UploadFilled">
                {{ editingPage.officialAudioUrl ? '更换音频' : '上传音频' }}
              </el-button>
            </el-upload>

            <div v-if="editingPage.officialAudioUrl" class="audio-preview">
              <audio :src="editingPage.officialAudioUrl" controls style="width: 100%; margin-top: 10px;"></audio>
              <el-button size="small" type="danger" @click="removeAudio" style="margin-top: 10px;">
                删除音频
              </el-button>
            </div>

          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPageEdit">取消</el-button>
          <el-button type="primary" @click="savePageEdit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, UploadFilled } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
import request from '@/config/axios'
import { createBookSet, getNextBookSetId, updateBookSetBookCount, type BookSetCreateReqVO } from '@/api/reading/bookset'
import { batchCreatePictureBooks, type PictureBookCreateReqVO } from '@/api/reading/book'
import { batchCreateBookPages, type BookPageCreateReqVO } from '@/api/reading/page'

// 定义组件事件
const emit = defineEmits(['close', 'success'])

// 当前步骤
const currentStep = ref(0)

// 提交状态
const submitting = ref(false)

// 绘本集ID（从后端获取的真实ID）
const bookSetId = ref<number | null>(null)

// 定义类型接口
interface BookPage {
  id?: number
  pageNumber: number
  imageUrl: string
  imageWidth?: number
  imageHeight?: number
  textContent: string
  textLanguage?: string
  officialAudioUrl: string
  audioDuration?: number
  readingDifficulty?: string
  keyWords: string[]
}

interface Book {
  id?: number
  title: string
  description: string
  coverUrl: string
  sort: number
  pages: BookPage[]
}

// 绘本集数据
const bookSetData = reactive({
  basic: {
    title: '',
    description: '',
    coverUrl: '',
    categoryId: null as number | null,
    language: 'en',
    difficulty: '',
    ageRange: '',
    source: '',
    isRecommended: false,
    tags: [] as string[],
    author: '',
    publisher: ''
  },
  books: [] as Book[]
})

// 表单引用
const basicFormRef = ref()

// 选中的绘本索引
const selectedBookIndex = ref<number | null>(null)

// 绘本编辑相关
const bookEditVisible = ref(false)
const editingBookIndex = ref(-1)
const editingBook = ref<Book>({
  id: 0, // 添加ID字段
  title: '',
  description: '',
  coverUrl: '',
  sort: 1,
  pages: []
})
const bookFormRef = ref()

// 页面编辑相关
const pageEditVisible = ref(false)
const editingPageIndex = ref(-1)
const editingPage = ref<BookPage>({
  pageNumber: 1,
  imageUrl: '',
  textContent: '',
  textLanguage: 'english',
  officialAudioUrl: '',
  readingDifficulty: 'easy',
  keyWords: []
})
const pageFormRef = ref()
const keyWordsInput = ref('')

// 分类数据（与数据库保持一致，排除"全部"分类）
const categories = ref([
  // 英文分类
  { id: 2, name: '分级阅读', language: 'en', description: '按难度分级的英文阅读绘本' },
  { id: 3, name: '桥梁书', language: 'en', description: '从绘本过渡到章节书的桥梁读物' },
  { id: 4, name: '章节书', language: 'en', description: '适合独立阅读的英文章节书' },
  { id: 5, name: '其它', language: 'en', description: '其他类型的英文绘本' },

  // 中文分类
  { id: 12, name: '古诗词', language: 'zh', description: '中华古典诗词绘本' },
  { id: 13, name: '成语故事', language: 'zh', description: '成语典故和寓意故事' },
  { id: 14, name: '寓言故事', language: 'zh', description: '经典寓言和哲理故事' },
  { id: 15, name: '传统文化', language: 'zh', description: '中华传统文化绘本' },
  { id: 16, name: '科普知识', language: 'zh', description: '科学知识普及绘本' },
  { id: 17, name: '品德教育', language: 'zh', description: '品德修养和教育绘本' }
])

// 获取下一个绘本ID的API调用
const getNextBookId = async () => {
  try {
    const data = await request.get({ url: '/reading/admin/books/next-id' })
    return data
  } catch (error) {
    console.error('获取下一个绘本ID出错:', error)
    ElMessage.error('获取绘本ID失败，请稍后重试')
    return null
  }
}

// 批量获取绘本ID的API调用（前端自增方式）
const getBatchBookIds = async (count: number) => {
  try {
    // 获取第一个ID作为起始ID
    const firstId = await request.get({ url: '/reading/admin/books/next-id' })

    // 基于第一个ID生成连续的ID列表
    const idList: number[] = []
    for (let i = 0; i < count; i++) {
      idList.push(firstId + i)
    }

    return idList
  } catch (error) {
    console.error('获取绘本ID出错:', error)
    ElMessage.error('获取绘本ID失败，请稍后重试')
    return null
  }
}

// 获取下一个页面ID的API调用
const getNextPageId = async () => {
  try {
    const data = await request.get({ url: '/reading/admin/pages/next-id' })
    console.log('获取下一个页面ID成功:', data)
    return data
  } catch (error) {
    console.error('获取下一个页面ID出错:', error)
    return null
  }
}

// 获取下一个音频ID的API调用
const getNextAudioId = async () => {
  try {
    const data = await request.get({ url: '/reading/audio-file/next-id' })
    console.log('获取下一个音频ID成功:', data)
    return data
  } catch (error) {
    console.error('获取下一个音频ID出错:', error)
    return null
  }
}

// 业务上传配置 - 绘本路径管理
const getBusinessUploadUrl = (type: 'bookset-cover' | 'book-cover' | 'page-image' | 'page-audio', bookSetId?: string | number, bookId?: string | number, pageNumber?: number) => {
  const baseUrl = import.meta.env.VITE_BASE_URL
  let uploadUrl = ''

  switch (type) {
    case 'bookset-cover':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${bookSetId || 0}/cover`
      break
    case 'book-cover':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${bookSetId || 0}/book/${bookId || 0}/cover`
      break
    case 'page-image':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${bookSetId || 0}/book/${bookId || 0}/page/${pageNumber || 1}`
      break
    case 'page-audio':
      uploadUrl = `${baseUrl}/admin-api/reading/book-file/book-set/${bookSetId || 0}/book/${bookId || 0}/audio?pageNumber=${pageNumber || 1}`
      break
    default:
      uploadUrl = import.meta.env.VITE_UPLOAD_URL
  }

  // 打印详细的文件路径信息到控制台
  console.log('=== 文件上传路径信息 ===')
  console.log('上传类型:', type)
  console.log('绘本集ID:', bookSetId)
  console.log('绘本ID:', bookId)
  console.log('页码:', pageNumber)
  console.log('完整上传URL:', uploadUrl)
  console.log('MinIO存储路径预览:')

  switch (type) {
    case 'bookset-cover':
      console.log('  -> book-sets/covers/' + (bookSetId || 0) + '/')
      break
    case 'book-cover':
      console.log('  -> books/covers/set-' + (bookSetId || 0) + '/book-' + (bookId || 0) + '/')
      break
    case 'page-image':
      console.log('  -> books/pages/set-' + (bookSetId || 0) + '/book-' + (bookId || 0) + '/page-' + (pageNumber || 1) + '/')
      break
    case 'page-audio':
      console.log('  -> books/audios/set-' + (bookSetId || 0) + '/book-' + (bookId || 0) + '/page-' + (pageNumber || 1) + '/')
      break
  }
  console.log('========================')

  return uploadUrl
}

// 业务上传模式说明：
// 1. 绘本集封面: /app-api/reading/book-file/bookset/{bookSetId}/cover
// 2. 绘本封面: /app-api/reading/book-file/bookset/{bookSetId}/book/{bookId}/cover
// 3. 页面图片: /app-api/reading/book-file/bookset/{bookSetId}/book/{bookId}/page/{pageNumber}/image
// 4. 页面音频: /app-api/reading/book-file/bookset/{bookSetId}/book/{bookId}/page/{pageNumber}/audio
// 这样可以实现文件的分类存储和路径管理

// 业务上传头部
const getBusinessUploadHeaders = () => ({
  Authorization: 'Bearer ' + getAccessToken()
  // 注意：不要手动设置 Content-Type，让浏览器自动设置 multipart/form-data 和 boundary
})

// 获取当前绘本ID
const getCurrentBookId = async () => {
  if (selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]) {
    // 如果绘本还没有ID，获取下一个真实ID
    if (!bookSetData.books[selectedBookIndex.value].id || bookSetData.books[selectedBookIndex.value].id === 0) {
      const nextBookId = await getNextBookId()
      if (nextBookId) {
        bookSetData.books[selectedBookIndex.value].id = nextBookId
        ElMessage.info(`已为绘本分配ID: ${nextBookId}`)
      } else {
        ElMessage.error('无法获取绘本ID')
        return 0
      }
    }
    return bookSetData.books[selectedBookIndex.value].id
  }
  // 如果没有选中的绘本，获取一个新的ID
  const nextBookId = await getNextBookId()
  return nextBookId || 0
}

// 为所有绘本预分配ID（前端智能分配，确保唯一性）
const preAllocateBookIds = async () => {
  // 统计需要分配ID的绘本数量
  const booksNeedingIds = bookSetData.books.filter(book => !book.id || book.id === 0)

  if (booksNeedingIds.length === 0) {
    return true
  }

  try {
    // 获取起始ID
    let startId: number
    const existingIds = bookSetData.books.filter(book => book.id && book.id > 0).map(book => book.id!)

    if (existingIds.length > 0) {
      // 如果已有绘本有ID，从最大ID + 1开始
      startId = Math.max(...existingIds) + 1
    } else {
      // 如果没有绘本有ID，从后端获取新的起始ID
      startId = await getNextBookId()
      if (!startId) {
        ElMessage.error('绘本ID预分配失败，请重试')
        return false
      }
    }

    // 为需要ID的绘本分配连续ID
    let currentId = startId
    for (let i = 0; i < bookSetData.books.length; i++) {
      const book = bookSetData.books[i]
      if (!book.id || book.id === 0) {
        book.id = currentId
        currentId++
      }
    }

    return true
  } catch (error) {
    console.error('绘本ID预分配失败:', error)
    ElMessage.error('绘本ID预分配失败，请重试')
    return false
  }
}

// 生成文件路径预览
const getFilePathPreview = (type: string, bookSetId?: string, bookId?: string, pageNumber?: number) => {
  const base = '/reading/booksets'
  switch (type) {
    case 'bookset-cover':
      return `${base}/${bookSetId}/cover/`
    case 'book-cover':
      return `${base}/${bookSetId}/books/${bookId}/cover/`
    case 'page-image':
      return `${base}/${bookSetId}/books/${bookId}/pages/${pageNumber}/image/`
    case 'page-audio':
      return `${base}/${bookSetId}/books/${bookId}/pages/${pageNumber}/audio/`
    default:
      return '/uploads/general/'
  }
}

// 表单验证规则
const basicFormRules = {
  title: [
    { required: true, message: '请输入绘本集标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  language: [
    { required: true, message: '请选择语言类型', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  ageRange: [
    { required: true, message: '请选择或输入适龄范围', trigger: 'blur' },
    {
      pattern: /^(\d+)-(\d+)岁?$/,
      message: '请输入正确的年龄范围格式，如：3-6岁',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        const match = value.match(/^(\d+)-(\d+)岁?$/)
        if (match) {
          const startAge = parseInt(match[1])
          const endAge = parseInt(match[2])
          if (startAge >= endAge) {
            callback(new Error('起始年龄应小于结束年龄'))
          } else if (startAge < 0 || endAge > 18) {
            callback(new Error('年龄范围应在0-18岁之间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  description: [
    { required: true, message: '请输入绘本集描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  source: [
    { max: 100, message: '来源长度不能超过 100 个字符', trigger: 'blur' }
  ],
  coverUrl: [
    { required: true, message: '请上传绘本集封面', trigger: 'change' }
  ]
}

// 绘本表单验证规则
const bookFormRules = {
  title: [
    { required: true, message: '请输入绘本标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '排序必须在 1 到 100 之间', trigger: 'blur' }
  ]
}

// 页面表单验证规则
const pageFormRules = {
  pageNumber: [
    { required: true, message: '请输入页面编号', trigger: 'blur' },
    { type: 'number' as const, min: 1, max: 100, message: '页面编号必须在 1 到 100 之间', trigger: 'blur' }
  ],
  textContent: [
    { max: 1000, message: '文本内容长度不能超过 1000 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const currentBook = computed((): Book => {
  if (selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]) {
    return bookSetData.books[selectedBookIndex.value]
  }
  return {
    title: '',
    description: '',
    coverUrl: '',
    sort: 1,
    pages: []
  }
})

const totalPages = computed(() => {
  return bookSetData.books.reduce((total, book) => {
    return total + (book.pages?.length || 0)
  }, 0)
})

// 根据语言类型筛选分类
const filteredCategories = computed(() => {
  const language = bookSetData.basic.language
  if (!language) return []

  // 根据语言筛选对应的分类
  return categories.value.filter(category => category.language === language)
})

// 监听语言类型变化，自动重置分类选择
watch(() => bookSetData.basic.language, (newLanguage, oldLanguage) => {
  if (newLanguage !== oldLanguage && bookSetData.basic.categoryId) {
    // 检查当前选择的分类是否还在新的筛选结果中
    const currentCategoryExists = filteredCategories.value.some(
      category => category.id === bookSetData.basic.categoryId
    )

    if (!currentCategoryExists) {
      // 如果当前分类不在新的筛选结果中，重置为空
      bookSetData.basic.categoryId = null
      ElMessage.info(`语言类型已更改为${getLanguageText(newLanguage)}，请重新选择分类`)
    }
  }
})

const canProceed = computed(() => {
  switch (currentStep.value) {
    case 0:
      const basic = bookSetData.basic
      const checks = {
        title: basic.title && basic.title.trim() !== '',
        description: basic.description && basic.description.trim() !== '',
        coverUrl: basic.coverUrl && basic.coverUrl.trim() !== '',
        language: basic.language && basic.language.trim() !== '',
        categoryId: basic.categoryId !== null && basic.categoryId !== undefined,
        difficulty: basic.difficulty && basic.difficulty.trim() !== '',
        ageRange: basic.ageRange && basic.ageRange.trim() !== '',
        // source字段是可选的，不需要验证
        // isRecommended字段是布尔值，不需要验证
      }

      // 调试信息
      console.log('第一步验证状态:', checks)
      console.log('当前数据:', basic)

      // 验证必填字段
      return checks.title && checks.description && checks.coverUrl &&
             checks.language && checks.categoryId && checks.difficulty && checks.ageRange
    case 1:
      return bookSetData.books.length > 0
    case 2:
      return totalPages.value > 0
    case 3:
      return true
    default:
      return false
  }
})

const validationResult = computed(() => {
  if (canProceed.value) {
    return {
      title: '验证通过',
      type: 'success' as const,
      description: '所有必填信息已完善，可以提交创建绘本集。'
    }
  } else {
    return {
      title: '验证失败',
      type: 'error' as const,
      description: '请完善当前步骤的必填信息。'
    }
  }
})

// 方法函数
const nextStep = () => {
  if (canProceed.value && currentStep.value < 3) {
    currentStep.value++
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const getValidationTagType = () => {
  if (canProceed.value) return 'success'
  return 'warning'
}

const getValidationText = () => {
  if (canProceed.value) return '验证通过'
  return '待完善'
}

const getLanguageText = (language: string) => {
  const map = {
    'en': '英文',
    'zh': '中文'
  }
  return map[language] || language
}

// 格式化适龄范围输入
const formatAgeRange = (value: string) => {
  if (!value) return value

  // 自动添加"岁"后缀
  if (/^\d+-\d+$/.test(value)) {
    return value + '岁'
  }

  return value
}

// 处理适龄范围变化
const handleAgeRangeChange = (value: string) => {
  if (value) {
    bookSetData.basic.ageRange = formatAgeRange(value)
  }
}

// 处理适龄范围失焦
const handleAgeRangeBlur = () => {
  if (bookSetData.basic.ageRange) {
    bookSetData.basic.ageRange = formatAgeRange(bookSetData.basic.ageRange)
  }
}

// 文件上传相关
const beforeCoverUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleCoverSuccess = (response: any) => {
  if (response.code === 0) {
    bookSetData.basic.coverUrl = response.data
    ElMessage.success('封面上传成功!')

    // 打印文件上传成功信息
    console.log('=== 绘本集封面上传成功 ===')
    console.log('绘本集ID:', bookSetId.value)
    console.log('文件URL:', response.data)
    console.log('MinIO存储路径:', `book-sets/covers/${bookSetId.value}/`)
    console.log('===========================')
  } else {
    ElMessage.error('封面上传失败: ' + response.msg)
    console.error('绘本集封面上传失败:', response)
  }
}

// 绘本管理相关
const addBook = async () => {
  try {
    // 计算下一个可用的ID
    let nextId: number

    if (bookSetData.books.length === 0) {
      // 如果没有绘本，获取一个新的起始ID
      nextId = await getNextBookId()
      if (!nextId) {
        ElMessage.error('无法获取绘本ID，请稍后重试')
        return
      }
    } else {
      // 如果已有绘本，基于最大ID + 1
      const maxId = Math.max(...bookSetData.books.map(book => book.id || 0))
      nextId = maxId + 1
    }

    const newBook: Book = {
      id: nextId, // 使用计算出的唯一ID
      title: '',
      description: '',
      coverUrl: '',
      sort: bookSetData.books.length + 1,
      pages: []
    }

    bookSetData.books.push(newBook)
    ElMessage.success(`绘本添加成功，请编辑绘本信息`)
  } catch (error) {
    console.error('添加绘本失败:', error)
    ElMessage.error('添加绘本失败，请稍后重试')
  }
}

const editBook = (index: number) => {
  editingBookIndex.value = index
  const book = bookSetData.books[index]

  // 深拷贝绘本数据到编辑表单，包含ID
  editingBook.value = {
    id: book.id, // 确保包含ID字段
    title: book.title || '',
    description: book.description || '',
    coverUrl: book.coverUrl || '',
    sort: book.sort || index + 1,
    pages: [...(book.pages || [])]
  }

  bookEditVisible.value = true
}

const removeBook = (index: number) => {
  ElMessageBox.confirm('确定要删除这个绘本吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    bookSetData.books.splice(index, 1)
    ElMessage.success('绘本删除成功')
  })
}

// 绘本编辑相关方法
const saveBookEdit = async () => {
  if (!bookFormRef.value) return

  try {
    await bookFormRef.value.validate()

    // 检查排序是否重复
    const existingSortIndex = bookSetData.books.findIndex((book, index) =>
      book.sort === editingBook.value.sort && index !== editingBookIndex.value
    )

    if (existingSortIndex !== -1) {
      ElMessage.warning(`排序 ${editingBook.value.sort} 已被绘本 "${bookSetData.books[existingSortIndex].title}" 使用，请选择其他排序`)
      return
    }

    // 更新绘本数据
    const book = bookSetData.books[editingBookIndex.value]
    book.id = editingBook.value.id // 确保保存ID
    book.title = editingBook.value.title
    book.description = editingBook.value.description
    book.coverUrl = editingBook.value.coverUrl
    book.sort = editingBook.value.sort



    // 按排序重新排列绘本
    bookSetData.books.sort((a, b) => (a.sort || 0) - (b.sort || 0))

    bookEditVisible.value = false
    ElMessage.success('绘本信息保存成功!')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const cancelBookEdit = () => {
  bookEditVisible.value = false
  editingBookIndex.value = -1
  editingBook.value = {
    id: 0, // 重置ID
    title: '',
    description: '',
    coverUrl: '',
    sort: 1,
    pages: []
  }
}

// 绘本封面上传URL（动态计算）
const bookCoverUploadUrl = computed(() => {
  return getBusinessUploadUrl('book-cover', bookSetId.value || 0, editingBook.value?.id || 0)
})

// 页面图片上传URL（动态计算）
const pageImageUploadUrl = computed(() => {
  const currentBookId = selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]
    ? bookSetData.books[selectedBookIndex.value].id || 0
    : 0
  return getBusinessUploadUrl('page-image', bookSetId.value || 0, currentBookId, editingPage.value?.pageNumber || 1)
})

// 页面音频上传URL（动态计算）
const pageAudioUploadUrl = computed(() => {
  const currentBookId = selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]
    ? bookSetData.books[selectedBookIndex.value].id || 0
    : 0
  return getBusinessUploadUrl('page-audio', bookSetId.value || 0, currentBookId, editingPage.value?.pageNumber || 1)
})

// 绘本封面上传前处理
const beforeBookCoverUpload = async (file: any) => {
  // 检查编辑中的绘本是否有有效ID
  if (editingBook.value?.id && editingBook.value.id > 0) {
    // 调用原有的文件验证逻辑
    return beforeCoverUpload(file)
  }

  // 如果编辑中的绘本没有ID，说明预分配可能失败，尝试重新预分配
  if (!await preAllocateBookIds()) {
    ElMessage.error('绘本ID预分配失败，请稍后重试')
    return false
  }

  // 检查预分配后是否有ID
  if (!editingBook.value?.id || editingBook.value.id === 0) {
    ElMessage.error('绘本ID预分配失败，请检查绘本数据')
    return false
  }

  // 调用原有的文件验证逻辑
  return beforeCoverUpload(file)
}

// 页面图片上传前处理
const beforePageImageUpload = async (file: any) => {
  // 确保所有绘本都有预分配的ID
  if (!await ensureBookHasId()) {
    return false
  }

  // 调用原有的文件验证逻辑
  return beforeImageUpload(file)
}

// 确保当前绘本有ID（使用预分配机制）
const ensureBookHasId = async () => {
  if (selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]) {
    const currentBook = bookSetData.books[selectedBookIndex.value]

    // 如果绘本已经有有效的ID，直接返回true
    if (currentBook.id && currentBook.id > 0) {
      return true
    }

    // 如果当前绘本没有ID，说明预分配失败，需要重新预分配
    if (!await preAllocateBookIds()) {
      ElMessage.error('绘本ID预分配失败，请稍后重试')
      return false
    }

    // 检查预分配后是否有ID
    if (!currentBook.id || currentBook.id === 0) {
      ElMessage.error('绘本ID预分配失败，请检查绘本数据')
      return false
    }

    return true
  }
  ElMessage.error('请先选择绘本')
  return false
}

// 页面音频上传前处理
const beforePageAudioUpload = async (file: any) => {
  // 确保所有绘本都有预分配的ID
  if (!await ensureBookHasId()) {
    return false
  }

  // 调用原有的文件验证逻辑
  return beforeAudioUpload(file)
}

// 绘本封面上传成功回调
const handleBookCoverSuccess = (response: any) => {
  if (response.code === 0) {
    editingBook.value.coverUrl = response.data
    ElMessage.success('绘本封面上传成功!')


  } else {
    // 检查是否是因为临时ID导致的错误
    if (response.msg && response.msg.includes('请先保存')) {
      ElMessage.warning('请先保存绘本集和绘本信息后再上传封面')
    } else {
      ElMessage.error('绘本封面上传失败: ' + response.msg)
    }
    console.error('绘本封面上传失败:', response)
  }
}

// 页面管理相关
const addPage = () => {
  if (selectedBookIndex.value === null) return

  const newPage: BookPage = {
    id: 0, // 临时ID，创建后会从数据库获取真实ID
    pageNumber: currentBook.value.pages.length + 1,
    imageUrl: '',
    textContent: '',
    officialAudioUrl: '',
    keyWords: []
  }

  if (!currentBook.value.pages) {
    currentBook.value.pages = []
  }

  currentBook.value.pages.push(newPage)
  ElMessage.success('页面添加成功，请编辑页面内容')
}

const editPage = (pageIndex: number) => {
  if (selectedBookIndex.value === null) return

  editingPageIndex.value = pageIndex
  const page = currentBook.value.pages[pageIndex]

  // 深拷贝页面数据到编辑表单
  editingPage.value = {
    id: page.id,
    pageNumber: page.pageNumber || pageIndex + 1,
    imageUrl: page.imageUrl || '',
    textContent: page.textContent || '',
    officialAudioUrl: page.officialAudioUrl || '',
    keyWords: [...(page.keyWords || [])]
  }

  // 设置关键词输入框
  keyWordsInput.value = editingPage.value.keyWords.join(', ')

  pageEditVisible.value = true
}

const removePage = (pageIndex: number) => {
  ElMessageBox.confirm('确定要删除这个页面吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    currentBook.value.pages.splice(pageIndex, 1)
    // 重新排序页码
    currentBook.value.pages.forEach((page, index) => {
      page.pageNumber = index + 1
    })
    ElMessage.success('页面删除成功')
  })
}

// 页面编辑相关方法
const savePageEdit = async () => {
  if (!pageFormRef.value) return

  try {
    await pageFormRef.value.validate()

    if (selectedBookIndex.value === null) return

    // 检查页面编号是否重复
    const existingPageIndex = currentBook.value.pages.findIndex((page, index) =>
      page.pageNumber === editingPage.value.pageNumber && index !== editingPageIndex.value
    )

    if (existingPageIndex !== -1) {
      ElMessage.warning(`页面编号 ${editingPage.value.pageNumber} 已存在，请选择其他编号`)
      return
    }

    // 更新页面数据
    const page = currentBook.value.pages[editingPageIndex.value]
    page.pageNumber = editingPage.value.pageNumber
    page.imageUrl = editingPage.value.imageUrl
    page.textContent = editingPage.value.textContent
    page.officialAudioUrl = editingPage.value.officialAudioUrl
    page.keyWords = [...editingPage.value.keyWords]

    // 按页面编号重新排序
    currentBook.value.pages.sort((a, b) => (a.pageNumber || 0) - (b.pageNumber || 0))

    pageEditVisible.value = false
    ElMessage.success('页面信息保存成功!')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const cancelPageEdit = () => {
  pageEditVisible.value = false
  editingPageIndex.value = -1
  editingPage.value = {
    pageNumber: 1,
    imageUrl: '',
    textContent: '',
    officialAudioUrl: '',
    keyWords: []
  }
  keyWordsInput.value = ''
}

// 关键词处理
const updateKeyWords = () => {
  if (keyWordsInput.value.trim()) {
    const keywords = keyWordsInput.value.split(',').map(k => k.trim()).filter(k => k)
    editingPage.value.keyWords = [...new Set(keywords)] // 去重
  } else {
    editingPage.value.keyWords = []
  }
}

const removeKeyword = (index: number) => {
  editingPage.value.keyWords.splice(index, 1)
  keyWordsInput.value = editingPage.value.keyWords.join(', ')
}

// 页面图片上传
const handlePageImageSuccess = (response: any) => {
  if (response.code === 0) {
    editingPage.value.imageUrl = response.data
    ElMessage.success('页面图片上传成功!')

    // 获取当前绘本ID（同步方式）
    const currentBookId = selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]
      ? bookSetData.books[selectedBookIndex.value].id || 0
      : 0

    // 打印文件上传成功信息
    console.log('=== 绘本页面图片上传成功 ===')
    console.log('绘本集ID:', bookSetId.value)
    console.log('绘本ID:', currentBookId)
    console.log('页码:', editingPage.value.pageNumber)
    console.log('文件URL:', response.data)
    console.log('MinIO存储路径:', `books/pages/set-${bookSetId.value}/book-${currentBookId}/page-${editingPage.value.pageNumber}/`)
    console.log('=============================')
  } else {
    ElMessage.error('页面图片上传失败: ' + response.msg)
    console.error('页面图片上传失败:', response)
  }
}

const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 音频上传
const handleAudioSuccess = (response: any) => {
  if (response.code === 0) {
    editingPage.value.officialAudioUrl = response.data
    ElMessage.success('音频上传成功!')

    // 获取当前绘本ID（同步方式）
    const currentBookId = selectedBookIndex.value !== null && bookSetData.books[selectedBookIndex.value]
      ? bookSetData.books[selectedBookIndex.value].id || 0
      : 0

    // 打印文件上传成功信息
    console.log('=== 绘本页面音频上传成功 ===')
    console.log('绘本集ID:', bookSetId.value)
    console.log('绘本ID:', currentBookId)
    console.log('页码:', editingPage.value.pageNumber)
    console.log('文件URL:', response.data)
    console.log('MinIO存储路径:', `books/audios/set-${bookSetId.value}/book-${currentBookId}/page-${editingPage.value.pageNumber}/`)
    console.log('=============================')
  } else {
    ElMessage.error('音频上传失败: ' + response.msg)
    console.error('音频上传失败:', response)
  }
}

const beforeAudioUpload = (file: File) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAudio) {
    ElMessage.error('只能上传音频格式的文件!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('上传音频大小不能超过 50MB!')
    return false
  }
  return true
}

const removeAudio = () => {
  editingPage.value.officialAudioUrl = ''
  ElMessage.success('音频已删除')
}

// 关闭和提交
const handleClose = () => {
  ElMessageBox.confirm('确定要关闭吗？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('close')
  })
}

const handleSubmit = async () => {
  if (!canProceed.value) {
    ElMessage.warning('请完善所有必填信息')
    return
  }

  submitting.value = true
  try {
    // 准备绘本集创建数据
    const createReqVO: BookSetCreateReqVO = {
      title: bookSetData.basic.title,
      cover: bookSetData.basic.coverUrl,
      description: bookSetData.basic.description,
      categoryId: bookSetData.basic.categoryId!,
      ageRange: bookSetData.basic.ageRange,
      source: bookSetData.basic.source || undefined, // 使用新的source字段
      difficultyLevel: bookSetData.basic.difficulty,
      language: bookSetData.basic.language,
      isRecommended: bookSetData.basic.isRecommended, // 使用新的isRecommended字段
      isActive: true
    }

    console.log('=== 开始创建绘本集 ===')
    console.log('绘本集ID:', bookSetId.value)
    console.log('创建数据:', createReqVO)
    console.log('绘本数量:', bookSetData.books.length)
    console.log('========================')

    // 验证绘本集ID是否有效
    if (!bookSetId.value) {
      throw new Error('绘本集ID无效，请刷新页面重试')
    }

    // 调用真实API创建绘本集
    await createBookSet(createReqVO)

    // 检查所有绘本是否都有预分配的ID
    if (bookSetData.books.length > 0) {
      const booksWithoutIds = bookSetData.books.filter(book => !book.id || book.id === 0)
      if (booksWithoutIds.length > 0) {
        if (!await preAllocateBookIds()) {
          ElMessage.error('绘本ID预分配失败，请重试')
          return
        }
      }
    }

    // 创建绘本数据
    if (bookSetData.books.length > 0) {
      const bookCreateReqVOs: PictureBookCreateReqVO[] = bookSetData.books.map(book => ({
        title: book.title,
        description: book.description,
        cover: book.coverUrl,
        bookSetId: bookSetId.value!,
        language: bookSetData.basic.language,
        difficultyLevel: bookSetData.basic.difficulty,
        sortOrder: book.sort,
        isActive: true
      }))


      const bookResponse = await batchCreatePictureBooks(bookCreateReqVOs)
      // 注意：由于axios响应拦截器的处理，bookResponse已经是后端返回的data字段
      const realBookIds = bookResponse as number[]



      // 更新绘本集的绘本数量
      await updateBookSetBookCount(bookSetId.value!)

      // 创建页面数据
      const allPageCreateReqVOs: BookPageCreateReqVO[] = []
      bookSetData.books.forEach((book, bookIndex) => {
        const realBookId = realBookIds[bookIndex]
        book.pages.forEach(page => {
          allPageCreateReqVOs.push({
            bookId: realBookId,
            pageNumber: page.pageNumber,
            imageUrl: page.imageUrl,
            imageWidth: page.imageWidth,
            imageHeight: page.imageHeight,
            textContent: page.textContent,
            textLanguage: page.textLanguage || 'english',
            officialAudioUrl: page.officialAudioUrl,
            audioDuration: page.audioDuration,
            readingDifficulty: page.readingDifficulty || 'easy',
            keyWords: page.keyWords
          })
        })
      })

      if (allPageCreateReqVOs.length > 0) {
        await batchCreateBookPages(allPageCreateReqVOs)

      }
    } else {
      // 如果没有绘本，也要更新绘本集的绘本数量为0
      await updateBookSetBookCount(bookSetId.value!)
    }

    console.log('========================')

    ElMessage.success('绘本集创建成功!')
    emit('success', { id: bookSetId.value, ...createReqVO })
  } catch (error: any) {
    console.error('创建绘本集失败:', error)
    ElMessage.error('创建失败: ' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 初始化绘本集ID
const initializeBookSetId = async () => {
  try {
    console.log('=== 获取绘本集ID ===')
    const response = await getNextBookSetId()
    bookSetId.value = response as number
    console.log('获取到绘本集ID:', bookSetId.value)
    console.log('==================')
  } catch (error) {
    console.error('获取绘本集ID失败:', error)
    ElMessage.error('获取绘本集ID失败，请刷新页面重试')
  }
}



// 组件挂载时初始化
onMounted(() => {
  initializeBookSetId()
})
</script>

<style scoped>
.bookset-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.step-navigation {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  flex-shrink: 0;
}

.main-content {
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.edit-area {
  height: 100%;
  overflow-y: auto;
  padding-right: 10px;
}

.step-content {
  min-height: auto;
  padding-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 基本信息样式 */
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
  width: 200px;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-uploader .el-upload:hover {
  border-color: #409eff;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-placeholder {
  text-align: center;
  color: #8c939d;
}

.cover-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.cover-text {
  font-size: 14px;
}

/* 适龄范围样式 */
.age-range-container {
  .age-range-tips {
    margin-top: 8px;
    padding: 8px 12px;
    /* background: #f0f9ff; */
    /* border: 1px solid #e0f2fe; */
    border-radius: 6px;

    .el-text {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }
}

/* 分类提示样式 */
.category-tips {
  margin-top: 8px;
  padding: 8px 12px;
  /* background: #f0f9ff; */
  /* border: 1px solid #e0f2fe; */
  border-radius: 6px;

  .el-text {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

/* 绘本管理样式 */
.empty-state {
  text-align: center;
  padding: 40px 0;
}

.books-list {
  margin-top: 20px;
}

.book-card {
  height: 100%;
}

.book-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.book-actions .el-button {
  margin-left: 5px;
}

.book-display {
  text-align: center;
}

.book-cover-container {
  margin-bottom: 15px;
}

.book-cover {
  width: 100px;
  height: 140px;
  object-fit: cover;
  border-radius: 6px;
}

.book-info h4 {
  margin: 10px 0 5px 0;
  font-size: 14px;
  color: #303133;
}

.book-description {
  font-size: 12px;
  color: #606266;
  margin: 5px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.book-stats {
  margin-top: 10px;
}

/* 页面管理样式 */
.pages-container {
  margin-top: 20px;
}

.pages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.page-card {
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.page-actions .el-button {
  margin-left: 5px;
}

.page-display {
  text-align: center;
}

.page-image-container {
  margin-bottom: 15px;
}

.page-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 6px;
}

.image-placeholder {
  width: 200px;
  height: 150px;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  margin: 0 auto;
}

.page-content {
  text-align: left;
}

.text-content p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.audio-info {
  margin-top: 8px;
  font-size: 12px;
}

.label {
  color: #606266;
  margin-right: 5px;
}

/* 预览区域样式 */
.preview-area {
  height: 97%;
}

.preview-card {
  height: 100%;
}

.preview-card .el-card__body {
  height: calc(100% - 60px);
  overflow-y: auto;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-content {
  height: 100%;
}

.step-preview h4 {
  margin-bottom: 15px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.preview-cover {
  width: 80px;
  height: 120px;
  object-fit: cover;
  border-radius: 6px;
  margin-bottom: 15px;
}

.info-section {
  text-align: left;
}

.info-item {
  margin-bottom: 8px;
  font-size: 13px;
}

.info-item .label {
  color: #606266;
  margin-right: 8px;
  font-weight: 500;
}

.empty-preview {
  text-align: center;
  padding: 30px 0;
}

.books-preview {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
}

.book-preview-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
}

.book-cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.no-cover {
  width: 40px;
  height: 60px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #909399;
}

.book-title {
  font-size: 13px;
  color: #303133;
  margin-bottom: 5px;
}

.pages-stats {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #606266;
}

.final-stats {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.stat-card {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-card .stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-card .stat-label {
  font-size: 12px;
  color: #606266;
}

/* 最终预览样式 */
.final-preview {
  padding: 20px 0;
}

.bookset-overview {
  margin-bottom: 20px;
}

.bookset-overview h3 {
  margin-bottom: 15px;
  color: #303133;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

/* 底部操作栏 */
.footer-actions {
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  text-align: right;
  flex-shrink: 0;
  background: white;
}

.footer-actions .el-button {
  margin-left: 10px;
}

/* 绘本编辑弹窗样式 */
.book-edit-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.book-cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
  width: 120px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.book-cover-uploader .el-upload:hover {
  border-color: #409eff;
}

.book-cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-cover-placeholder {
  text-align: center;
  color: #8c939d;
}

.book-cover-placeholder .cover-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.book-cover-placeholder .cover-text {
  font-size: 12px;
}

/* 页面编辑弹窗样式 */
.page-edit-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.page-image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
  width: 300px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-image-uploader .el-upload:hover {
  border-color: #409eff;
}

.page-image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.page-image-placeholder {
  text-align: center;
  color: #8c939d;
}

.page-image-placeholder .upload-icon {
  font-size: 28px;
  margin-bottom: 10px;
}

.page-image-placeholder .upload-text {
  font-size: 14px;
}

.keywords-display {
  margin-top: 8px;
}

.audio-upload-container {
  .audio-preview {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    background: #f8f9fa;
    width: 400px;
  }
}

.audio-uploader .el-upload {
  display: inline-block;
}

/* 新字段样式 */
.source-tips, .recommend-tips {
  margin-top: 5px;
}

.source-tips .el-text, .recommend-tips .el-text {
  font-size: 12px;
}

/* 推荐开关样式优化 */
.el-form-item .el-switch {
  margin-right: 10px;
}

</style>
